package com.sjf.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjf.common.CustomException;
import com.sjf.common.Result;
import com.sjf.reggie.entity.Category;
import com.sjf.reggie.entity.Dish;
import com.sjf.reggie.entity.Setmeal;
import com.sjf.reggie.mapper.CategoryMapper;
import com.sjf.reggie.mapper.DishMapper;
import com.sjf.reggie.mapper.SetmealMapper;
import com.sjf.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author <huangtang>
 * @since 2022/4/26 10:28
 **/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetmealMapper setmealMapper;

    @Override
    public Page<Category> selectList ( Integer pageNum , Integer pageSize ) {
        Page<Category> pageInfo = new Page<> (pageNum , pageSize);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<> ();
        queryWrapper.lambda ().orderByAsc (Category::getSort);
        return  page (pageInfo,queryWrapper);
    }

    @Override
    public boolean deleteById ( Long id ) {
        //查询分类是否关联了菜品和套餐
        QueryWrapper<Dish> dishWrp = new QueryWrapper<> ();
        dishWrp.lambda ().eq (Dish::getCategoryId , id);
        Integer dishCount  = dishMapper.selectCount (dishWrp);
        if (dishCount > 0) {
            throw new CustomException ("该分类已关联菜品，不能删除");
        }
        //查询分类是否关联了套餐
        QueryWrapper<Setmeal> setmealWrp = new QueryWrapper<> ();
        setmealWrp.lambda ().eq (Setmeal::getCategoryId , id);
        Integer setmealCount = setmealMapper.selectCount (setmealWrp);
        if (setmealCount > 0) {
            throw new CustomException ("该分类已关联套餐，不能删除");
        }
        return removeById (id);
    }

    @Override
    public List<Category> getList (Category category ) {
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<> ();
        categoryQueryWrapper.lambda ().eq (category.getType ()!=null,Category::getType,category.getType ())
                .orderByAsc (Category::getSort)
                .orderByDesc (Category::getUpdateTime);
        return categoryMapper.selectList (categoryQueryWrapper);
    }
}
